import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

import { User } from '../entity/User';

@Injectable()
export class UserService {
    private userUrl = '/api/User/GetUser';
    private user: User;

    constructor(private http: HttpClient) {}

    getUser() {
        const item = localStorage.getItem('user');
        if (item == '') {
            return null;
        }
        return JSON.parse(item) as User;
    }
    // 验证账户和密码
    validateUser(email: string, password: string) {
        return this.http
            .get(`${this.userUrl}?email=${email}&password=${password}`)
            .subscribe(response => {
                this.user = response as User;
                localStorage.setItem('user', JSON.stringify(this.user));
            });
    }

    logOff() {
        this.user = null;
        localStorage.setItem('user', null);
    }
}
